package fun.ticsmyc.rpc.client.util;

import fun.ticsmyc.rpc.common.entity.RpcRequest;
import fun.ticsmyc.rpc.common.entity.RpcResponse;
import fun.ticsmyc.rpc.common.enumeration.ResponseCode;
import fun.ticsmyc.rpc.common.enumeration.RpcError;
import fun.ticsmyc.rpc.common.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Ticsmyc
 * @date 2020-10-30 9:51
 */
public class RpcMessageChecker {
    public static final Logger logger = LoggerFactory.getLogger(RpcMessageChecker.class);

    private RpcMessageChecker(){}

    public static void check(RpcRequest rpcRequest, RpcResponse<Object> rpcResponse){
        if(rpcResponse == null){
            logger.error("调用服务失败,seriviceName = {}",rpcRequest.getInterfaceName());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, " 服务名："+rpcRequest.getInterfaceName());
        }
        if(!rpcRequest.getRequestId().equals(rpcResponse.getRequestId())){
            throw new RpcException(RpcError.RESPONSE_NOT_MATCH," 服务名："+rpcRequest.getInterfaceName());
        }
        if(rpcResponse.getStatusCode()==null ||!rpcResponse.getStatusCode().equals(ResponseCode.SUCCESS.getCode())){
            logger.error("调用服务失败,seriviceName = {} , response = {}",rpcRequest.getInterfaceName(),rpcResponse);
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, " 服务名："+rpcRequest.getInterfaceName()+" 响应："+rpcResponse);

        }
    }

}
